<template>
  <div id="userCenterPage">
    <div class="page-container">
      <div class="profile-card">
        <!-- 头部区域 -->
        <div class="profile-header">
          <div class="header-left">
            <a-avatar :src="userInfo.userAvatar" :size="100" />
          </div>
          <div class="header-right">
            <h2 class="user-name">{{ userInfo.userName || '未命名' }}</h2>
            <div class="user-meta">
              <a-tag :color="userInfo.userRole === 'admin' ? 'green' : 'blue'">
                {{ userInfo.userRole === 'admin' ? '管理员' : '普通用户' }}
              </a-tag>
              <span class="user-account">{{ userInfo.userAccount }}</span>
            </div>
            <div class="user-stats">
              <div class="stat-item">
                <i class="stat-icon"><CalendarOutlined /></i>
                <span>注册于 {{ userInfo.createTime ? dayjs(userInfo.createTime).format('YYYY-MM-DD') : '-' }}</span>
              </div>
              <div class="stat-item">
                <i class="stat-icon"><IdcardOutlined /></i>
                <span>用户ID: {{ userInfo.id || '-' }}</span>
              </div>
            </div>
          </div>
          <div class="header-actions">
            <a-button type="primary" @click="startEditing" v-if="!isEditing">
              <template #icon><EditOutlined /></template>
              编辑资料
            </a-button>
          </div>
        </div>

        <!-- 内容区域 -->
        <div class="profile-body">
          <a-spin :spinning="loading">
            <!-- 编辑表单 -->
            <div v-if="isEditing" class="edit-form">
              <h3 class="section-title">编辑个人资料</h3>
              <a-form :model="editForm" layout="vertical">
                <a-form-item label="用户名">
                  <a-input v-model:value="editForm.userName" placeholder="请输入用户名" />
                </a-form-item>
                <a-form-item label="头像">
                  <div class="avatar-upload-container">
                    <a-upload
                      name="avatar"
                      list-type="picture-card"
                      class="avatar-uploader"
                      :show-upload-list="false"
                      :before-upload="beforeUpload"
                      accept="image/*"
                    >
                      <div class="upload-area">
                        <a-spin v-if="avatarUploading" />
                        <template v-else>
                          <a-avatar
                            v-if="editForm.userAvatar"
                            :src="editForm.userAvatar"
                            :size="100"
                            class="preview-avatar"
                          />
                          <div v-else class="upload-placeholder">
                            <PlusOutlined />
                            <div class="upload-text">点击上传头像</div>
                          </div>
                        </template>
                      </div>
                    </a-upload>
                    <div class="upload-tips">
                      <p>• 支持 JPG、JPEG、PNG、GIF 格式</p>
                      <p>• 图片大小不超过 5MB</p>
                    </div>
                  </div>
                </a-form-item>
                <a-form-item label="个人简介">
                  <a-textarea 
                    v-model:value="editForm.userProfile" 
                    placeholder="请输入个人简介" 
                    :rows="4"
                  />
                </a-form-item>
                <a-form-item>
                  <a-space>
                    <a-button type="primary" @click="saveChanges" :loading="saving">
                      保存
                    </a-button>
                    <a-button @click="cancelEditing">
                      取消
                    </a-button>
                  </a-space>
                </a-form-item>
              </a-form>
            </div>

            <!-- 用户信息展示 -->
            <div v-else class="user-info">
              <div class="info-section">
                <h3 class="section-title">个人资料</h3>
                
                <div class="info-card">
                  <div class="info-item">
                    <div class="info-label">用户名</div>
                    <div class="info-value">{{ userInfo.userName || '未设置' }}</div>
                  </div>
                  
                  <div class="info-item">
                    <div class="info-label">账号</div>
                    <div class="info-value">{{ userInfo.userAccount }}</div>
                  </div>
                  
                  <div class="info-item">
                    <div class="info-label">用户角色</div>
                    <div class="info-value">
                      <a-tag :color="userInfo.userRole === 'admin' ? 'green' : 'blue'">
                        {{ userInfo.userRole === 'admin' ? '管理员' : '普通用户' }}
                      </a-tag>
                    </div>
                  </div>
                  
                  <div class="info-item">
                    <div class="info-label">注册时间</div>
                    <div class="info-value">{{ userInfo.createTime ? dayjs(userInfo.createTime).format('YYYY-MM-DD HH:mm:ss') : '-' }}</div>
                  </div>
                </div>
              </div>
              
              <div class="info-section">
                <h3 class="section-title">个人简介</h3>
                <div class="profile-box">
                  {{ userInfo.userProfile || '这个人很懒，还没有填写个人简介' }}
                </div>
              </div>
            </div>
          </a-spin>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { getLoginUser, updateSelf, uploadAvatar } from '@/api/userController.ts'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import dayjs from 'dayjs'
import { EditOutlined, CalendarOutlined, IdcardOutlined, UploadOutlined, PlusOutlined } from '@ant-design/icons-vue'

// 用户信息
const userInfo = reactive<API.UserVO>({
  id: '',
  userName: '',
  userAccount: '',
  userAvatar: '',
  userProfile: '',
  userRole: '',
  createTime: '',
})

// 加载状态
const loading = ref(true)
const saving = ref(false)

// 编辑状态
const isEditing = ref(false)
const editForm = reactive<API.UserSelfUpdateRequest>({
  userName: '',
  userAvatar: '',
  userProfile: '',
})

// 头像上传状态
const avatarUploading = ref(false)

const loginUserStore = useLoginUserStore()

// 获取用户信息
const fetchUserInfo = async () => {
  loading.value = true
  try {
    const res = await getLoginUser()
    if (res.data.code === 0 && res.data.data) {
      const userData = res.data.data
      // 填充用户信息
      userInfo.id = userData.id
      userInfo.userAccount = userData.userAccount
      userInfo.userName = userData.userName
      userInfo.userAvatar = userData.userAvatar
      userInfo.userProfile = userData.userProfile
      userInfo.userRole = userData.userRole
      userInfo.createTime = userData.createTime
    } else {
      message.error('获取用户信息失败')
    }
  } catch (error) {
    message.error('获取用户信息失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 开始编辑
const startEditing = () => {
  isEditing.value = true
  // 填充表单
  editForm.userName = userInfo.userName
  editForm.userAvatar = userInfo.userAvatar
  editForm.userProfile = userInfo.userProfile
}

// 保存更改
const saveChanges = async () => {
  saving.value = true
  try {
    const res = await updateSelf(editForm)
    if (res.data.code === 0) {
      message.success('更新成功')
      isEditing.value = false
      // 刷新数据
      fetchUserInfo()
      // 更新全局用户信息
      if (loginUserStore.loginUser) {
        loginUserStore.setLoginUser({
          ...loginUserStore.loginUser,
          userName: editForm.userName,
          userAvatar: editForm.userAvatar,
        })
      }
    } else {
      message.error('更新失败：' + res.data.message)
    }
  } catch (error) {
    message.error('更新失败，请检查网络连接')
  } finally {
    saving.value = false
  }
}

// 处理头像上传
const handleAvatarUpload = async (file: File) => {
  // 验证文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件！')
    return false
  }

  // 验证文件大小 (5MB)
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    message.error('图片大小不能超过 5MB！')
    return false
  }

  avatarUploading.value = true
  
  try {
    const res = await uploadAvatar(file)
    if (res.data.code === 0 && res.data.data) {
      editForm.userAvatar = res.data.data
      message.success('头像上传成功')
      return true
    } else {
      message.error('头像上传失败：' + res.data.message)
      return false
    }
  } catch (error) {
    message.error('头像上传失败，请检查网络连接')
    return false
  } finally {
    avatarUploading.value = false
  }
}

// 头像上传前的处理
const beforeUpload = (file: File) => {
  handleAvatarUpload(file)
  return false // 阻止自动上传
}

// 取消编辑
const cancelEditing = () => {
  isEditing.value = false
}

// 页面加载时获取用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
#userCenterPage {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 64px);
}

.page-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
}

.profile-card {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.profile-header {
  padding: 32px;
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  color: white;
  display: flex;
  position: relative;
}

.header-left {
  margin-right: 24px;
}

.header-right {
  flex: 1;
}

.header-actions {
  position: absolute;
  top: 32px;
  right: 32px;
}

.user-name {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: white;
}

.user-meta {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.user-account {
  margin-left: 12px;
  opacity: 0.9;
}

.user-stats {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  opacity: 0.9;
}

.stat-icon {
  margin-right: 6px;
  display: flex;
  align-items: center;
}

.profile-body {
  padding: 32px;
}

.section-title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin: 0 0 16px 0;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.info-section {
  margin-bottom: 32px;
}

.info-section:last-child {
  margin-bottom: 0;
}

.info-card {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.info-item {
  flex: 1;
  min-width: 200px;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.info-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.info-value {
  font-size: 16px;
  color: #333;
}

.profile-box {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  line-height: 1.6;
  white-space: pre-line;
}

.edit-form {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 20px;
}

@media (max-width: 768px) {
  .profile-header {
    flex-direction: column;
    align-items: center;
    text-align: center;
    padding: 24px;
  }
  
  .header-left {
    margin-right: 0;
    margin-bottom: 16px;
  }
  
  .header-actions {
    position: static;
    margin-top: 16px;
  }
  
  .user-meta {
    justify-content: center;
  }
  
  .user-stats {
    justify-content: center;
  }
  
  .info-item {
    min-width: 100%;
  }
}

/* 头像上传样式 */
.avatar-upload-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.avatar-uploader {
  display: inline-block;
}

.upload-area {
  width: 100px;
  height: 100px;
  border: 2px dashed #d9d9d9;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: #fafafa;
  overflow: hidden;
}

.upload-area:hover {
  border-color: #1890ff;
  background-color: #f0f8ff;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #666;
}

.upload-placeholder .anticon {
  font-size: 24px;
  margin-bottom: 4px;
}

.upload-text {
  font-size: 12px;
  text-align: center;
}

.preview-avatar {
  width: 100% !important;
  height: 100% !important;
  object-fit: cover;
}

.upload-tips {
  color: #666;
  font-size: 12px;
  line-height: 1.4;
}

.upload-tips p {
  margin: 0;
}

/* 覆盖 ant-design-vue 的默认样式 */
:deep(.avatar-uploader .ant-upload.ant-upload-select-picture-card) {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: none;
  background: transparent;
}

:deep(.avatar-uploader .ant-upload.ant-upload-select-picture-card:hover) {
  border: none;
}
</style>